package com.sky.handler;

import com.alibaba.fastjson.JSON;
import com.sky.domain.Result;
import com.sky.exception.CaptchaException;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @projectName: netty-cloud
 * @package: com.sky.handler
 * @className: MyMyAuthenticationFailureHandler
 * @author: zhl
 * @description: 实现本方法，替换security登录失败后自动跳转页面的处理方式
 * @date: 2024/4/25 11:42
 * @version: 1.0
 */
@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
    /**
     * Called when an authentication attempt fails.
     *
     * @param request   the request during which the authentication attempt occurred.
     * @param response  the response.
     * @param exception the exception which was thrown to reject the authentication
     *                  request.
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = response.getOutputStream();

        String errorMessage = "用户名或密码错误";
        Result result;
        if (exception instanceof CaptchaException) {
            errorMessage = "验证码错误";
            result = Result.failure(errorMessage);
        } else {
            result = Result.failure(errorMessage);
        }
        outputStream.write(JSON.toJSONString(result).getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
